'''
Created on 7 mai 2010

@author: philip
'''

import logging
import hashlib
from urllib import urlopen
from xml.dom import minidom
from django.http import HttpResponse, Http404
from django.utils.simplejson import JSONEncoder
from settings import FLICKR_API_KEY, FLICKR_API_SECRET
from photo_service import PhotoService, AddPhotoRequest, GetPhotosRequest
from django.shortcuts import render_to_response
from communities.community_service import CommunityService

def index(request,communityId):
    community = CommunityService().getCommunity(communityId)
    if community is None: raise Http404
    photos = PhotoService().getPhotos(GetPhotosRequest(community.urlName))
    return render_to_response("photos/photos.html",{"community":community, "photos":photos})

def add_photo(request):
    image_meta = {}
    
    for k,v in request.REQUEST.items():
        image_meta[k] = v
    
    logging.info("adding photo: %s" % request.REQUEST)
    
    #TODO: adapt for other services (e.g. kavadenn)
    r = AddPhotoRequest(request.REQUEST["community_id"], "flickr",request.REQUEST["title"],
                        request.REQUEST["thumb"],request.REQUEST["medium"], request.REQUEST["original"], image_meta)
    photo = PhotoService().addPhoto(r)
    
    return HttpResponse(JSONEncoder().encode({"status":"ok","id":photo.id}),mimetype="application/json")  

def get_photo(request,photoId):
    photo = PhotoService().getPhotoById(photoId)
    return render_to_response("photos/photo_pane.html",{"photo":photo})

def flickr_get_token(request):
    frob = request.GET["frob"]
    signature = hashlib.md5("%sapi_key%sfrob%smethod%s" % (FLICKR_API_SECRET,FLICKR_API_KEY,frob,"flickr.auth.getToken")).hexdigest()
    
    url = "http://api.flickr.com/services/rest/?method=%s&api_key=%s&frob=%s&api_sig=%s" % ("flickr.auth.getToken",FLICKR_API_KEY,frob,signature)
    
    d = minidom.parse(urlopen(url))
    
    token = {"token":d.getElementsByTagName("token")[0].firstChild.nodeValue}
    
    return HttpResponse(JSONEncoder().encode(token),mimetype="application/json")

def flickr_get_frob(request):
    signature = hashlib.md5("%sapi_key%smethod%s" % (FLICKR_API_SECRET,FLICKR_API_KEY,"flickr.auth.getFrob")).hexdigest()

    url="http://api.flickr.com/services/rest/?method=flickr.auth.getFrob&api_key=%s&api_sig=%s" % (FLICKR_API_KEY,signature)
    d = minidom.parse(urlopen(url))
    
    frob = {"frob":d.getElementsByTagName("frob")[0].firstChild.nodeValue}
    
    return HttpResponse(JSONEncoder().encode(frob),mimetype="application/json")


#def get(request,photo_id):
#    pic = getPicture(photo_id)
#    return HttpResponse(pic, content_type='application/octet-stream')
#
#def getSmallThumb(request,photo_id):
#    pic = getPicture(photo_id,"small")
#    return HttpResponse(pic, content_type='application/octet-stream')
#
#def getMediumThumb(request,photo_id):
#    pic = getPicture(photo_id,"medium")
#    return HttpResponse(pic, content_type='application/octet-stream')
#
#
#def upload(request):
#    UPLOAD_LIMIT = 1048576 #1 Mb in bytes
#
#    try:
#        if not request.FILES.has_key("picture"):
#            raise Exception("no file is uploaded or file is too big")
#              
#        uploadSize = request.FILES["picture"].size
#        logging.debug("image size: %s bytes" % uploadSize)
#        
#        if uploadSize > UPLOAD_LIMIT: 
#            raise Exception("file is too big")
#        
#        image = request.FILES["picture"].read()
#        photo = addPhoto(image)
#        if photo is not None:
#            smallThumbUrl = "http://%s/photos/get-st/%s/" % (request.META["HTTP_HOST"],photo.id) 
#            mediumThumbUrl = "http://%s/photos/get-mt/%s/" % (request.META["HTTP_HOST"],photo.id)
#            return HttpResponse(JSONEncoder().encode({"status" : "ok", 
#                                                      "smallThumb" : smallThumbUrl, 
#                                                      "mediumThumb" : mediumThumbUrl}))
#        else:
#            raise Exception("failed to add image")
#    except Exception, x:
#        logging.error("image upload failed: %s %s" % (x,x.__class__))
#        return HttpResponse(JSONEncoder().encode({"status" : "error"}))